package com.sunyur.tailor.channel.service.outer.keep.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import com.sunyur.tailor.channel.common.inner.base.MsgResultCode;
import com.sunyur.tailor.channel.common.middle.base.ChannelListResult;
import com.sunyur.tailor.channel.common.middle.base.ChannelResult;
import com.sunyur.tailor.channel.common.middle.enums.MiddleResultEnum;
import com.sunyur.tailor.channel.common.middle.util.ChannelResultUtil;
import com.sunyur.tailor.channel.service.inner.purchase.model.PurchaserApplyHeadModel;
import com.sunyur.tailor.channel.service.inner.purchase.model.PurchaserApplyItemModel;
import com.sunyur.tailor.channel.service.inner.purchase.param.PurchaseApplyHeadByCodeParam;
import com.sunyur.tailor.channel.service.inner.purchase.param.PurchaseApplyItemsByCodeParam;
import com.sunyur.tailor.channel.service.inner.purchase.service.SunyurPurchaseApplyService;
import com.sunyur.tailor.channel.service.outer.keep.param.FeishuForApprovalFormParam;
import com.sunyur.tailor.channel.service.outer.keep.param.SRMPurchaseFeishuForApprovalParam;
import com.sunyur.tailor.channel.service.outer.keep.service.KeepToFeishuService;
import com.sunyur.tailor.channel.service.outer.keep.service.WorkflowBusinessStrategyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

/**
 *   ApplyOrder策略
 */
@Service("applyOrder")
@Slf4j
public class ApplyOrderStrategyImpl implements WorkflowBusinessStrategyService {
    @Autowired
    SunyurPurchaseApplyService sunyurPurchaseApplyService;
    @Autowired
    KeepToFeishuService keepToFeishuService;

    @Value("${feishu.applyOrder.approvalCode}")
    private String approvalCode;


    // TODO 这里是否考虑再套一层策略模式 还是继续if else (if else 可以提高效率)
    @Override
    public ChannelResult start(MsgResultCode msgResultCode) {
        if(("commit").equals(msgResultCode.getAction()))
        {


            ChannelResult result=new ChannelResult<>();
            //根据申请单号获取申请单头部信息
            PurchaseApplyHeadByCodeParam purchaseApplyHeadByCodeParam = new PurchaseApplyHeadByCodeParam();
            purchaseApplyHeadByCodeParam.setApplyCode(msgResultCode.getBusinessCode());
            ChannelResult<PurchaserApplyHeadModel> purchaserApplyHeadByCode = sunyurPurchaseApplyService.getPurchaserApplyHeadByCode(purchaseApplyHeadByCodeParam);


            if (!ChannelResultUtil.isSuccess(purchaserApplyHeadByCode)) {
                result.setError(purchaserApplyHeadByCode.getCode(),purchaserApplyHeadByCode.getMessage());
                return result;
            }
            log.info("purchaserApplyHeadByCode:{}", JSONObject.toJSONString(purchaserApplyHeadByCode));
            //根据申请单号查询申请单行
            PurchaseApplyItemsByCodeParam purchaseApplyItemsByCodeParam = new PurchaseApplyItemsByCodeParam();
            purchaseApplyItemsByCodeParam.setApplyCode(msgResultCode.getBusinessCode());
            ChannelListResult<PurchaserApplyItemModel> purchaserApplyItemResult = sunyurPurchaseApplyService.getPurchaserApplyItemsHeadByCode(purchaseApplyItemsByCodeParam);

            if (!ChannelResultUtil.isSuccess(purchaserApplyItemResult)) {
                result.setError(purchaserApplyItemResult.getCode(),purchaserApplyItemResult.getMessage());
                return result;
            }
            List<PurchaserApplyItemModel> content = purchaserApplyItemResult.getContent();
            if (content == null || content.size() == 0) {
                result.setError(purchaserApplyItemResult.getCode(),purchaserApplyItemResult.getMessage());
                return result;
            }
            AtomicReference<BigDecimal> widget6Value= new AtomicReference<>(new BigDecimal(0));
            content.forEach(
                    c->{
                        log.info("c:{}",JSONObject.toJSONString(c));
                        if(c.getCount()==null||c.getPriceWithTax()==null){
                            result.setError(purchaserApplyItemResult.getCode(),"");

                            return;
                        }
                        BigDecimal itemTotal = c.getCount().multiply(c.getPriceWithTax()); //单价*数量
                        widget6Value.updateAndGet(v->v.add(itemTotal));
                    }
            );
            log.info("content:{}",JSONObject.toJSONString(content));

            SRMPurchaseFeishuForApprovalParam srmPurchaseFeishuForApprovalParam = new SRMPurchaseFeishuForApprovalParam();
            //拼装请求参数
            srmPurchaseFeishuForApprovalParam.setApproval_code(approvalCode); //固定值
            srmPurchaseFeishuForApprovalParam.setUser_id(purchaserApplyHeadByCode.getContent().getProposerCode()); //申请人id
            srmPurchaseFeishuForApprovalParam.setOpen_id(purchaserApplyHeadByCode.getContent().getProposerCode()); //PR头/content/proposerCode
            ArrayList formList = new ArrayList();

            //widget1
            FeishuForApprovalFormParam widget1=new FeishuForApprovalFormParam();
            widget1.setId("widget1");
            widget1.setType("input");
            widget1.setValue(purchaserApplyHeadByCode.getContent().getApplyName()); //Value取值PR申请单的名称 PR头/content/applyName
            //widget2
            FeishuForApprovalFormParam widget2=new FeishuForApprovalFormParam();
            widget2.setId("widget2");
            widget2.setType("contact");
            widget2.setValue(Arrays.asList(purchaserApplyHeadByCode.getContent().getProposerCode())); //Value取值PR提交人的账号 PR头/content/proposerCode
            //widget3
            FeishuForApprovalFormParam widget3=new FeishuForApprovalFormParam();
            widget3.setId("widget3");
            widget3.setType("input");
            widget3.setValue(purchaserApplyHeadByCode.getContent().getProposerOrgName());
            //widget4
            FeishuForApprovalFormParam widget4=new FeishuForApprovalFormParam();
            widget4.setId("widget4");
            widget4.setType("input");
            widget4.setValue(purchaserApplyHeadByCode.getContent().getCompanyName());//PR单上的主体字段 PR头/content/companyName
            //widget5
            FeishuForApprovalFormParam widget5=new FeishuForApprovalFormParam();
            widget5.setId("widget5");
            widget5.setType("textarea");
            widget5.setValue(purchaserApplyHeadByCode.getContent().getApplyDescribe()+" ");//PR单上的主体字段 PR头/content/applyDescribe
            //widget6
            FeishuForApprovalFormParam widget6=new FeishuForApprovalFormParam();
            widget6.setId("widget6");
            widget6.setType("input");
            widget6.setValue(widget6Value.get().setScale(2,BigDecimal.ROUND_HALF_UP).toString());//PR单上的主体字段 PR头/content/applyDescribe
            //widget7
            FeishuForApprovalFormParam widget7=new FeishuForApprovalFormParam();
            widget7.setId("widget7");
            widget7.setType("fieldList");
            widget7.setValue(widget7Value(purchaserApplyItemResult));
            //widget8
            FeishuForApprovalFormParam widget8=new FeishuForApprovalFormParam();
            widget8.setId("widget8");
            widget8.setType("input");
            widget8.setValue(purchaserApplyHeadByCode.getContent().getApplyCode());

            formList.add(widget1);
            formList.add(widget2);
            formList.add(widget3);
            formList.add(widget4);
            formList.add(widget5);
            formList.add(widget6);
            formList.add(widget7);
            formList.add(widget8);

            srmPurchaseFeishuForApprovalParam.setForm(JSONObject.toJSONString(formList));

            //创建审批实例
            ChannelResult<Boolean> booleanChannelResult = keepToFeishuService.sRMPurchaseFeishuForApproval(msgResultCode,srmPurchaseFeishuForApprovalParam);

            return booleanChannelResult;
        }
        return ChannelResultUtil.error(MiddleResultEnum.FAILED.getCode(), "参数错误");

    }

    public List<List<FeishuForApprovalFormParam>> widget7Value(ChannelListResult<PurchaserApplyItemModel> channelListResult){
        List<PurchaserApplyItemModel> content = channelListResult.getContent();
        List first = new ArrayList();
        content.forEach(
                c->{
                    List two = new ArrayList();
                    FeishuForApprovalFormParam widget1=new FeishuForApprovalFormParam();
                    widget1.setId("widget7_1");
                    widget1.setType("input");
                    widget1.setValue(c.getMaterialName());
                    FeishuForApprovalFormParam widget2=new FeishuForApprovalFormParam();
                    widget2.setId("widget7_2");
                    widget2.setType("input");
                    widget2.setValue(c.getCount().setScale(2,RoundingMode.HALF_UP).toString()); //保留两位小数
                    FeishuForApprovalFormParam widget3=new FeishuForApprovalFormParam();
                    widget3.setId("widget7_3");
                    widget3.setType("input");
                    //四舍五入
                    widget3.setValue(c.getCount().multiply(c.getPriceWithTax()).setScale(2,RoundingMode.HALF_UP).toString()); //保留两位小数
                    FeishuForApprovalFormParam widget4=new FeishuForApprovalFormParam();
                    widget4.setId("widget7_4");
                    widget4.setType("input");
                    widget4.setValue(DateUtil.format(c.getExpectDeliveryDate(), "yyyy-MM-dd"));
                    FeishuForApprovalFormParam widget5=new FeishuForApprovalFormParam();
                    widget5.setId("widget7_5");
                    widget5.setType("textarea");
                    widget5.setValue(c.getInnerFile()==null?"":c.getInnerFile());
                    two.add(widget1);
                    two.add(widget2);
                    two.add(widget3);
                    two.add(widget4);
                    two.add(widget5);
                    first.add(two);
                }
        );


        return first;
    }
}

